package com.das.mechanic_base.widget;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.core.content.FileProvider;

import com.das.mechanic_base.R;
import com.das.mechanic_base.app.X3Constent;
import com.das.mechanic_base.bean.verison.ChangeVersion;
import com.das.mechanic_base.utils.X3DateUtils;
import com.das.mechanic_base.utils.X3FileUtils;
import com.das.mechanic_base.utils.SpHelper;
import com.das.mechanic_base.utils.X3StringUtils;
import com.das.mechanic_base.utils.X3VersionUtils;
import com.downloader.Error;
import com.downloader.OnDownloadListener;
import com.downloader.PRDownloader;
import com.umeng.analytics.MobclickAgent;

import java.io.File;

/**
 * Created by chensi on 2018/6/1.
 */

public class X3UpdateAppDialog extends Dialog implements View.OnClickListener {

    private Point mScreenPoint = new Point();
    private Activity mRootActivity;
    private String versionName;

    private ImageView iv_dismiss;
    private TextView tv_title;
    private TextView tv_content;
    private TextView tv_affirm;
    private ProgressBar pb_update;
    private TextView tv_prograss;
    private ChangeVersion changeVersion;
    private int whichCountry;

    /**
     * 一个按钮Dialog
     *
     * @param arg
     */
    public X3UpdateAppDialog(Activity arg) {
        super(arg, R.style.pointDialog);
        mRootActivity = arg;
        PackageInfo packageInfo = null;
        try {
            packageInfo = mRootActivity.getPackageManager().getPackageInfo(mRootActivity.getPackageName(), 0);
            versionName = packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

    }

    @SuppressWarnings("deprecation")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setBackgroundDrawable(new BitmapDrawable());
        this.setContentView(R.layout.x3_update_app_dialog);

//        initDialogWindow();
        initView();
    }

    private void initView() {
        iv_dismiss = getView(R.id.iv_dismiss);
        tv_prograss = getView(R.id.tv_prograss);
        tv_title = getView(R.id.tv_title);
        tv_content = getView(R.id.tv_content);
        tv_affirm = getView(R.id.tv_affirm);
        pb_update = getView(R.id.pb_update);

        iv_dismiss.setOnClickListener(this);
        tv_affirm.setOnClickListener(this);
    }

    /**
     * 通过控件的Id获取对于的控件，如果没有则加入views
     *
     * @param viewId
     * @return
     */
    public <T extends View> T getView(int viewId) {
        View view = null;
        view = findViewById(viewId);
        return (T) view;
    }

    /**
     * 传入更新类型
     * @param
     */
    public void showDownType(String updateType,ChangeVersion changeVersion) {
        this.changeVersion = changeVersion;
        this.setCancelable(true);
        this.setCanceledOnTouchOutside(true);

        switch (updateType) {
            case X3Constent.FORCED_UPDATE:
                // 强制升级
                show();

                this.setCancelable(false);
                this.setCanceledOnTouchOutside(false);

                iv_dismiss.setVisibility(View.GONE);
                pb_update.setVisibility(View.GONE);
                tv_prograss.setVisibility(View.GONE);
                tv_affirm.setVisibility(View.VISIBLE);
                break;
            case X3Constent.STRONG_UPDATE:
                // 强提醒升级
                SpHelper.saveData(X3Constent.STRONG_REMINDER_RED + versionName,true);
                String remind_time = (String) SpHelper.getData(X3Constent.STRONG_REMINDER_TIME, "");

                if (X3StringUtils.isEmpty(remind_time)) {
                    show();
                    SpHelper.saveData(X3Constent.STRONG_REMINDER_TIME, X3DateUtils.getCurrentYearAndDay());
                    iv_dismiss.setVisibility(View.VISIBLE);
                    pb_update.setVisibility(View.GONE);
                    tv_prograss.setVisibility(View.GONE);
                    tv_affirm.setVisibility(View.VISIBLE);

                }else {
                    if (X3DateUtils.checkDayOrYear(remind_time)) {
                        show();
                        SpHelper.saveData(X3Constent.STRONG_REMINDER_TIME, X3DateUtils.getCurrentYearAndDay());
                        iv_dismiss.setVisibility(View.VISIBLE);
                        pb_update.setVisibility(View.GONE);
                        tv_prograss.setVisibility(View.GONE);
                        tv_affirm.setVisibility(View.VISIBLE);
                    }
                }

                break;
            default:
                // 弱提醒升级

                String weakApp = (String) SpHelper.getData(X3Constent.WEAK_REMINDER_APP, "");
                if (X3StringUtils.isEmpty(weakApp)) {
                    show();
                    SpHelper.saveData(X3Constent.WEAK_REMINDER_APP,versionName);
                    iv_dismiss.setVisibility(View.VISIBLE);
                    pb_update.setVisibility(View.GONE);
                    tv_prograss.setVisibility(View.GONE);
                    tv_affirm.setVisibility(View.VISIBLE);
                }else {
                    if (X3VersionUtils.compareVersions(weakApp,versionName) == 1) {
                        // 说明之前存储了版本 但是这次需要修改为最新的
                        show();
                        iv_dismiss.setVisibility(View.VISIBLE);
                        pb_update.setVisibility(View.GONE);
                        tv_prograss.setVisibility(View.GONE);
                        tv_affirm.setVisibility(View.VISIBLE);
                        SpHelper.saveData(X3Constent.WEAK_REMINDER_APP,versionName);
                    }
                }

                break;
        }
    }

    @SuppressWarnings("deprecation")
    private void initDialogWindow() {
        Window dialogWindow = getWindow();
        dialogWindow.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);

        WindowManager m = mRootActivity.getWindowManager();
        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用

        try {
            d.getSize(mScreenPoint);
        } catch (NoSuchMethodError ignore) {
            mScreenPoint.x = d.getWidth();
            mScreenPoint.y = d.getHeight();
        }

        WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
        p.width = (int) (mScreenPoint.x * 0.76);    // 宽度设置为屏幕的0.9
        dialogWindow.setAttributes(p);
    }

    /**
     * 跳转到设置-允许安装未知来源-页面
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    private void startInstallPermissionSettingActivity() {
        //注意这个是8.0新API
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mRootActivity.startActivity(intent);
    }

    @Override
    public void show() {
        super.show();
        whichCountry = X3Constent.isWhichCountry();
        if (changeVersion == null) {
            return;
        }
        if (0 == whichCountry) {
            tv_content.setText(changeVersion.descriptionInChina + "");
        }else if (1 == whichCountry) {
            tv_content.setText(changeVersion.descriptionInGermany + "");
        }else {
            tv_content.setText(changeVersion.description + "");
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_dismiss) {
            dismiss();
        } else if (id == R.id.tv_affirm) {// 更新
            File file;
            if (X3StringUtils.isEmpty(changeVersion.versionSuffix)) {
                file = new File(X3FileUtils.getStoragePath(mRootActivity, X3FileUtils.APP_STORAGE_PATH) + "MECHANIC_" + changeVersion.appVersion + ".apk");
            } else {
                file = new File(X3FileUtils.getStoragePath(mRootActivity, X3FileUtils.APP_STORAGE_PATH) + "MECHANIC_" + changeVersion.appVersion + "_" + changeVersion.versionSuffix + ".apk");
            }

            if (!file.exists()) {
                // 去下载
                downApp(file);
                return;
            }
            Intent intent = new Intent();
            //执行动作
            intent.setAction(Intent.ACTION_VIEW);
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
                Uri uri = FileProvider.getUriForFile(mRootActivity, mRootActivity.getPackageName() + ".fileprovider", file);
                //修改  downloadFile 来源于上面下载文件时保存下来的
                //  BuildConfig.APPLICATION_ID + ".fileprovider" 是在manifest中 Provider里的authorities属性定义的值
                Intent install = new Intent(Intent.ACTION_VIEW);
                install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                install.setDataAndType(uri, "application/vnd.android.package-archive");
                //兼容8.0
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    boolean hasInstallPermission = mRootActivity.getPackageManager().canRequestPackageInstalls();
                    if (!hasInstallPermission) {
                        startInstallPermissionSettingActivity();
                        mRootActivity.startActivity(install);
                        return;
                    }
                }
                mRootActivity.startActivity(install);
            } else {
                Intent install = new Intent(Intent.ACTION_VIEW);
                install.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
                install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mRootActivity.startActivity(install);
            }
        }
    }

    @Override
    public void dismiss() {
        super.dismiss();
        PRDownloader.cancelAll();
    }

    private void downApp(File file) {
        if (changeVersion == null) {
            dismiss();
            return;
        }
        tv_affirm.setVisibility(View.GONE);
        pb_update.setVisibility(View.VISIBLE);
        tv_prograss.setVisibility(View.VISIBLE);

        // 如果app还没有下载 开启下载
        PRDownloader.download(X3Constent.isChina() ? changeVersion.downloadUrlQiniu : changeVersion.downloadUrl, X3FileUtils.getStoragePath(mRootActivity, X3FileUtils.APP_STORAGE_PATH), file.getName())
                .build()
                .setOnProgressListener(progress -> {
                    int value = (int) (progress.currentBytes * 100 / progress.totalBytes);
                    if (pb_update != null) {
                        pb_update.setProgress(value);
                    }
                    if (tv_prograss != null) {
                        tv_prograss.setText(String.format(mRootActivity.getString(R.string.x3_current_update),value + "%"));
                    }
                })
                .start(new OnDownloadListener() {
                    @Override
                    public void onDownloadComplete() {
                        //TODO 提示用户安装
                        if (tv_affirm != null) {
                            tv_affirm.setVisibility(View.VISIBLE);
                        }
                        if (pb_update != null) {
                            pb_update.setVisibility(View.GONE);
                        }
                        if (tv_prograss != null) {
                            tv_prograss.setVisibility(View.GONE);
                        }
                    }

                    @Override
                    public void onError(Error error) {
                    }

                });
    }
    @Override
    protected void onStart() {
        super.onStart();
        MobclickAgent.onPageStart("app更新弹窗");
    }

    @Override
    protected void onStop() {
        super.onStop();
        MobclickAgent.onPageEnd("app更新弹窗");
    }
}
